﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using DAL;
using System.Collections;
using Facade.Excel;

namespace PeisongWeb.admin
{
    public partial class myCustomerReceivablesList : adminPage
    {
        protected int companyId
        {
            get
            {
                int tmp;
                try { tmp = Convert.ToInt32(ViewState["companyId"]); }
                catch { tmp = 0; }
                return tmp;
            }
            set
            { ViewState["companyId"] = value; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("IB", 1))
                {
                    if (Request.QueryString["company"] != null)
                    {
                        if (Library.Number.IsIntPositive(Request.QueryString["company"]))
                        {
                            companyId = Convert.ToInt32(Request.QueryString["company"]);
                            lt_company.Text = logic.company.getById(companyId).Company;
                        }
                    }
                    drpBind();
                    rptBind();
                    showCollect();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                    return;
                }

            }
        }
        void drpBind()
        {
            ddl_Type.DataSource = logic.sysCode.listWithPayStatus("1");
            ddl_Type.DataBind();
            ddl_Type.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }
        void rptBind()
        {
            StringBuilder where = new StringBuilder();
            where.Append("type='1' and companyId="+companyId);
            if (ddl_Type.SelectedValue != "")
                where.AppendFormat(" and status = '{0}'", ddl_Type.SelectedValue.Trim());
            if (ext_StartInputDt.SelectedDate!=DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[startDt],'{0}')<=0", ext_StartInputDt.SelectedDate);
            if (ext_EndInputDt.SelectedDate!=DateTime.MinValue)
                where.AppendFormat(" and datediff(day,[endDt],'{0}')>=0", ext_EndInputDt.SelectedDate);

            DataSet ds = logic.paymentHistory.select(where.ToString(), "payId desc", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_list.DataSource = ds.Tables[1];
            rpt_list.DataBind();
        }
        protected void rpt_list_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Details")
            {
                int payId = Convert.ToInt32(e.CommandArgument);

                PaymentHistoryEntity _phe = logic.paymentHistory.getByPayId(payId);
                hid_companyId.Value = _phe.CompanyId.ToString();
                hid_startDt.Value = _phe.StartDt.ToString();
                hid_endDt.Value = _phe.EndDt.ToString();
                hid_PayId.Value = payId.ToString();
                rptOrderItemBind(payId);
                orderItem.Show();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }
        protected void lbtn_Search_Click(object sender, EventArgs e)
        {
            rptBind();
            showCollect();
        }
        protected void AspNetPager2_PageChanged(object sender, EventArgs e)
        {
            int payId = Convert.ToInt32(hid_PayId.Value);
            rptOrderItemBind(payId);
        }
        void rptOrderItemBind(int payId)
        {
            int company = Convert.ToInt32(hid_companyId.Value);
            string startDt = hid_startDt.Value;
            string endDt = hid_endDt.Value;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("companyId={0} ", company);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", startDt);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", endDt);
            if (txt_orderNo.Text.Trim() != "")
                sb.AppendFormat("and orderno='{0}'", txt_orderNo.Text.Trim());
            DataSet ds = logic.orderItem.listWithOrder(sb.ToString(), "oiid", AspNetPager2.PageSize, AspNetPager2.CurrentPageIndex);
            AspNetPager2.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            rpt_orderItem.DataSource = ds.Tables[1];
            rpt_orderItem.DataBind();
            rpt_orderItemBind();
        }

        protected void lbn_select_Click(object sender, EventArgs e)
        {
            int payId = Convert.ToInt32(hid_PayId.Value);
            rptOrderItemBind(payId);
        }

        private DataSet orderItemByWhere()
        {
            //int company = Convert.ToInt32(hid_companyId.Value);
            string startDt = hid_startDt.Value;
            string endDt = hid_endDt.Value;
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("companyId={0} ", companyId);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')<=0", startDt);
            sb.AppendFormat(" and datediff(day,[updateStatusdt],'{0}')>=0", endDt);
            if (txt_orderNo.Text.Trim() != "")
                sb.AppendFormat("and orderno='{0}'", txt_orderNo.Text.Trim());
            DataSet ds = logic.orderItem.listwithReceivables(sb.ToString());
            return ds;
        }

        protected void lbn_Import_Click(object sender, EventArgs e)
        {
            DataSet ds = orderItemByWhere();
            DataTable dt=ds.Tables[0];
            dt.Columns["proName"].ColumnName = "商品";
            dt.Columns["quantity"].ColumnName = "数量";
            dt.Columns["price"].ColumnName = "单价";
            dt.Columns["unit"].ColumnName = "单位";
            dt.Columns["amount"].ColumnName = "小计";
            dt.Columns["orderNo"].ColumnName = "订单号";
            dt.Columns["statusName"].ColumnName = "订单状态";
            dt.Columns["updateStatusdt"].ColumnName = "成功日期";
            dt.Columns["receiveDt"].ColumnName = "收获日期";

            ExportFacade facade = new ExportFacade();
            Dictionary<int,FormatStyle> formatOptions=new Dictionary<int,FormatStyle>();
            formatOptions.Add(1, FormatStyle.ToFix2);
            formatOptions.Add(2, FormatStyle.ToFix2);
            formatOptions.Add(4, FormatStyle.ToFix2);
            facade.ExportByWeb(dt, "订单数据", "订单数据.xls", formatOptions, "订单数据");
        }

        private void showCollect()
        {
            DateTime? startDt = null;
            DateTime? endDt = null;
            if (ext_StartInputDt.SelectedDate != DateTime.MinValue) startDt = ext_StartInputDt.SelectedDate;
            if (ext_EndInputDt.SelectedDate != DateTime.MinValue) endDt = ext_EndInputDt.SelectedDate;

            CompanyEntity comEnt = logic.company.getById(companyId);
            string companyName = comEnt.Company;
            string companyNo =comEnt.CompanyNo;
            string paymethod =comEnt.PayMethod;

            DataRow dr = logic.paymentHistory.listWithCollectByFinancial(companyId, startDt, endDt, companyName, companyNo, paymethod, "1").Rows[0];
            lit_orderNum.Text = string.Format("{0:F2}", dr["orderNum"]);
            lit_payMoney.Text = string.Format("{0:F2}", dr["payMoney"]);
            lit_notPayMoney.Text = string.Format("{0:F2}", dr["notPayMoney"]);
            lit_total.Text = string.Format("{0:F2}", dr["orderAmount"]);
        }
        private void rpt_orderItemBind()
        {
            DataTable dt = orderItemByWhere().Tables[1];
            lbl_Total.Text = string.Format("{0:F2}", dt.Rows[0]["total"]);
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect("myCustomerList.aspx");
        }
    }
}
